import { Component, OnInit, Input } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { GridConfigService } from 'app/core/config/grid-config.service';
import { GridOptions } from '@ag-grid-community/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { ICellRendererParams } from '@ag-grid-community/core';
import { ExportExcelService } from '@core/services/excel/export-excel.service';
import { ApesMessageService } from '@shared/apes/message';
import { UserAuthService } from '@core/services/user-auth.service';
import * as CryptoJS from 'crypto-js';
import { BiService } from '../../bi.service';

@Component({
  selector: 'apes-sheet-metal-count',
  templateUrl: './sheet-metal-count.component.html',
  styleUrls: ['./sheet-metal-count.component.scss'],
})
export class SheetMetalCountComponent implements OnInit {
  /* 按钮相关 */
  buttonBar = [{ hide: true, style: 'default', label: '查询', id: 'action_query', loading: false },
    { hide: true, style: 'default', label: '展开查询条件', id: 'action_show', loading: false },
    { hide: true, style: 'default', label: '导出', id: 'action_export', api: '', loading: false },
    // {hide: true, style: 'default', label: '重置查询条件', id: 'action_reset'}
  ];
  title = '';
  ctx = { model: {} };

  /** Grid 相关 **/
  rowData: any[] = [];
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  getContextMenuItems: any;

  // 获取门店
  nxmdList: any[];
  arrNXMD = [];
  // 获取接车基地
  jcmdmcList: any[];
  arrJCMDMC = [];

  // 需传的值
  // selectedOption;    //测试
  ngWXLX: any;
  ngNXMD: any;
  ngJCMDMC: any;
  cphmName: any;
  ywyName: any;
  ngSFYTS: any;
  ngCLSGZT: any;
  ngBZSGZT: any;
  ngGX: any;
  ngSFYJC: any;
  ngTLC: any;

  mdjcTime: any = [];
  mdjcTime_ks = null;
  mdjcTime_js = null;
  jdjcTime: any = [];
  jdjcTime_ks = null;
  jdjcTime_js = null;
  yjjcTime: any = [];
  yjjcTime_ks = null;
  yjjcTime_js = null;
  dsqbwcTime: any = [];
  dsqbwcTime_ks = null;
  dsqbwcTime_js = null;
  pjqbdhTime: any = [];
  pjqbdhTime_ks = null;
  pjqbdhTime_js = null;
  jrsgdTime: any = [];
  jrsgdTime_ks = null;
  jrsgdTime_js = null;
  jcTime: any = [];
  jcTime_ks = null;
  jcTime_js = null;

  fwlxList: any[];
  arrFWLX = [];
  ngFWLX: any;

  hidn: any = 'none';
  height: any = window.innerHeight - 200 + 'px';

  params: ICellRendererParams;

  userInfo = this.userAuthService.getUserInfoObj();
  companyId = this.userInfo.userAccount.post.company.id;
  companyData:any;
  companyList: any[];
  ngCLZT: any;

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private router: Router,
              private exportExcelService: ExportExcelService,
              private msg: ApesMessageService,
              private userAuthService: UserAuthService,
              private routeInfo: ActivatedRoute,
              private bi: BiService) {

    this.columnDefs = [
      { 'headerName': '维修类型', field: 'WXLX', width: 120, pinned: 'left' },
      { 'headerName': '内协门店', field: 'NXMDMC', width: 150, pinned: 'left' },
      { 'headerName': '接车基地', field: 'JCMDMC' },
      { 'headerName': '车辆状态', field: 'CLZT' },
      { 'headerName': '车牌号码', field: 'CPHM', width: 120, pinned: 'left' },
      { 'headerName': '品牌', field: 'QCCPMC' },
      { 'headerName': '接车人', field: 'JDJIECR' },
      { 'headerName': '幅数', field: 'FS' },
      { 'headerName': '喷漆部位', field: 'PQBW' },
      { 'headerName': '钣金部位', field: 'BJBW' },
      { 'headerName': '门店接车时间', field: 'NXMDJCRQ_SJ' },
      { 'headerName': '基地接车时间', field: 'JDJCRQ_SJ' },
      { 'headerName': '基地预计交车', field: 'YJJCRQ_SJ' },
      { 'headerName': '定损全部完成时间', field: 'DSWCRQ_SJ' },
      { 'headerName': '配件全部到货时间', field: 'PJDHRQ_SJ' },
      { 'headerName': '进入施工端时间', field: 'JRSGDRQ_SJ' },
      { 'headerName': '已调色', field: 'SFYTS' },
      { 'headerName': '返修类型', field: 'FXLX' },
      { 'headerName': '服务类型', field: 'FWLX' },
      { 'headerName': '车辆施工状态', field: 'CLSGZT' },
      { 'headerName': '工序施工状态', field: 'GXSGZT' },
      { 'headerName': '工序', field: 'GX' },
      { 'headerName': '工序施工时长(分钟)', field: 'GXSGSC' },
      { 'headerName': '已交车', field: 'SFYJC' },
      { 'headerName': '交车时间', field: 'JCRQ_SJ' },
      { 'headerName': 'T+留存', field: 'TLC' },
      //{"headerName": "查看详情", field: "", editable: false, cellRendererFramework: RenderButtonViewComponent}
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 100,
      rowHeight: 35,
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.getContextMenuItems = function getContextMenuItems(params) {

      const result = [

        'copy',
        'separator',
        { name: params.value },
        'separator',
        {
          name: '查看详情',
          action: () => {
            let modal = {};
            let dataModal = params.node.data;
            let data = dataModal['CKXQ'];
            router.navigate(['/bi/door-tube-center/sheetMetalCount/sheetMetalDetail', data]);
          },
        },
      ];
      return result;
    };
    this.companyList = [];
    this.companyList.push(this.companyId);
  }

  ngOnInit() {
    //  解密
    this.routeInfo.queryParams.subscribe((params: Params) => {
      if (JSON.stringify(params) !== '{}') {
        let value = CryptoJS.enc.Base64.parse(params['value']);
        value = JSON.parse(value.toString(CryptoJS.enc.Utf8));
        this.getTablesData(value);
      }
      // else {
      //   this.getTablesData();
      // }


    });

    this.bi.getCompany(this.userInfo.userAccount.post.localPermit.id).then(value => { this.companyData = value });
    this.getNxmdData();
    this.getJcmdmcData();
    this.getFwjdData();
  }

  refresh(params: any): boolean {
    return undefined;
  }

  agInit(params: ICellRendererParams): void {
    this.params = params;
  }

  /**
   * 功能：按钮事件路由
   * @param data 当前按钮元数据
   */
  onEvent(data: any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.queryData();
        this.hidn = 'none';
      } else if (data.id === 'action_reset') {
        this.action_reset();
      } else if (data.id === 'action_show') {
        this.action_show();
      } else if (data.id === 'action_export') {
        this.action_export();
      }
    }
  }

  /**
   * 功能：导出Grid数据
   */
  action_export() {
    if (this.rowData && this.rowData.length === 0) {
      return;
    }
    const columnList = this.gridOptions.columnDefs;
    this.exportExcelService.exportWithDealData(columnList, this.rowData, '钣喷车辆明细');
  }

  /**
   * 功能：重置查询条件
   */
  action_reset(): void {
  }

  action_show() {
    if (this.hidn === 'none') {
      this.hidn = 'flex';
    } else if (this.hidn === 'flex') {
      this.hidn = 'none';
    }
  }

  queryData() {
    // if(this.companyList.length <= 0){
    //   this.companyList.push(this.companyId);
    // }
    this.getDate(this.mdjcTime, 'mdjcTime_ks', 'mdjcTime_js');
    this.getDate(this.jdjcTime, 'jdjcTime_ks', 'jdjcTime_js');
    this.getDate(this.yjjcTime, 'yjjcTime_ks', 'yjjcTime_js');
    this.getDate(this.dsqbwcTime, 'dsqbwcTime_ks', 'dsqbwcTime_js');
    this.getDate(this.pjqbdhTime, 'pjqbdhTime_ks', 'pjqbdhTime_js');
    this.getDate(this.jrsgdTime, 'jrsgdTime_ks', 'jrsgdTime_js');
    this.getDate(this.jcTime, 'jcTime_ks', 'jcTime_js');

    this.getTablesData();
    this.getNxmdData();
    this.getJcmdmcData();
  }

  getDate(time: any[], time_ks: string, time_js: string) {
    // debugger;
    let [first, second] = time;
    if (first) {
      this[time_ks] = first.toISOString().slice(0, 10);
    } else {
      this[time_ks] = null;
    }

    if (second) {
      this[time_js] = second.toISOString().slice(0, 10);
    } else {
      this[time_js] = null;
    }

  }

  getTablesData(data?: any) {
    if(data === undefined) {
      data = {
        'interfaceMethod': 'ipmBPforAppService.getBPLBData', 'pdata': {
          'tjJson': {
            'WXLX': this.ngWXLX, 'NXMDID': this.ngNXMD, 'JCJDID': this.ngJCMDMC,
            'CPHM': this.cphmName, 'JDJIECR': this.ywyName,
            'NXMDJCRQ_SJ_KS': this.mdjcTime_ks, 'NXMDJCRQ_SJ_JS': this.mdjcTime_js,
            'JDJCRQ_SJ_KS': this.jdjcTime_ks, 'JDJCRQ_SJ_JS': this.jdjcTime_js,
            'YJJCRQ_SJ_KS': this.yjjcTime_ks, 'YJJCRQ_SJ_JS': this.yjjcTime_js,
            'DSWCRQ_SJ_KS': this.dsqbwcTime_ks, 'DSWCRQ_SJ_JS': this.dsqbwcTime_js,
            'PJDHRQ_SJ_KS': this.pjqbdhTime_ks, 'PJDHRQ_SJ_JS': this.pjqbdhTime_js,
            'JRSGDRQ_SJ_KS': this.jrsgdTime_ks, 'JRSGDRQ_SJ_JS': this.jrsgdTime_js,
            'JCRQ_SJ_KS': this.jcTime_ks, 'JCRQ_SJ_JS': this.jcTime_js,
            'SFYTS': this.ngSFYTS, 'CLSGZT': this.ngCLSGZT, 'GXSGZT': this.ngBZSGZT, 'GX': this.ngGX,
            'SFYJC': this.ngSFYJC, 'TLC': this.ngTLC, 'FWLX': this.ngFWLX, 'companyId': this.companyList,
            'CLZT': this.ngCLZT,
          },
        },
      };
    }

    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let list = JSON.parse(result.obj);
            this.rowData = list;
            if (this.rowData.length === 0) {
              this.msg.info(`未找到满足条件的数据`);
            }
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取门店名称
  getNxmdData() {
    this.getJcmdmcData();
    let data = {
      'interfaceMethod': 'ipmBPforAppService.getSQMDXX', 'pdata': { 'MDBJ': true, 'companyId': this.companyList },
    };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        // debugger;
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.nxmdList = data;
            this.arrNXMD = this.nxmdList;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取接车基地名称
  getJcmdmcData() {
    let data = {
      'interfaceMethod': 'ipmBPforAppService.getSQMDXX', 'pdata': { 'JDBJ': true, 'companyId': this.companyList },
    };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        // debugger;
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.jcmdmcList = data;
            this.arrJCMDMC = this.jcmdmcList;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  getFwjdData() {
    let data = { 'interfaceMethod': 'ipmCLZKForAppService.getFWLX', 'pdata': {} };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.fwlxList = data;
            this.arrFWLX = this.fwlxList;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  arrWXLE = [
    { label: '自费', key: 0 },
    { label: '定损', key: 1 },
    { label: '全部', key: '' },
  ];

  arrSYF = [
    { label: '是', key: 1 },
    { label: '否', key: 0 },
    { label: '全部', key: '' },
  ];

  // 车辆状态
  arrCLZT = [
    { label: '定损中', key: 'DSZ' },
    { label: '制定服务方案', key: 'ZDFWFA' },
    { label: '待施工', key: 'DSG' },
    { label: '施工中', key: 'SGZ' },
    { label: '施工暂停', key: 'SGZT' },
    { label: '已完成', key: 'SGWC' },
  ];

  // 步骤
  arrGX = [
    { label: '调色', key: 0 },
    { label: '拆解', key: 1 },
    { label: '修复', key: 2 },
    { label: '做底', key: 3 },
    { label: '磨底', key: 4 },
    { label: '喷漆', key: 5 },
    { label: '装配', key: 6 },
    { label: '抛光', key: 7 },
    { label: '质检', key: 8 },
    { label: '全部', key: '' },
  ];

  // 车辆施工状态
  arrSGZT = [
    { label: '待到店', key: 0 },
    { label: '待施工', key: 1 },
    { label: '施工中', key: 2 },
    { label: '已完成', key: 3 },
    { label: '全部', key: '' },
  ];

  // 步骤施工状态w
  arrBZSGZT = [
    { label: '待施工', key: 1 },
    { label: '施工中', key: 2 },
    { label: '已完成', key: 3 },
    { label: '全部', key: '' },
  ];


}
